#include <iostream>
#include <vector>
#include <queue>

using namespace std;

struct TreeNode 
{
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode()
        : val(0)
        , left(nullptr)
        , right(nullptr)
    {}
    TreeNode(int x) 
        : val(x)
        , left(nullptr)
        , right(nullptr) 
    {}
    TreeNode(int x, TreeNode* left, TreeNode* right) 
        : val(x)
        , left(left)
        , right(right) 
    {}
};

class Solution
{
public:
    vector<vector<int>> levelOrder(TreeNode* root)
    {
        vector<vector<int>> vv;
        queue<TreeNode*> q;
        int levelSize = 0;
        if (root)
        {
            q.push(root);
            levelSize = 1;
        }
        while (!q.empty())
        {
            vector<int> v;
            while (levelSize--)
            {
                TreeNode* front = q.front();
                q.pop();
                v.push_back(front->val);

                if (front->left)
                {
                    q.push(front->left);
                }
                if (front->right)
                {
                    q.push(front->right);
                }               
            }
            vv.push_back(v);
            levelSize = q.size();
        }
        return vv;
    }
};


int main()
{
    TreeNode* A = new TreeNode(3);
    TreeNode* B = new TreeNode(9);
    A->left = B;
    TreeNode* C = new TreeNode(20);
    A->right = C;
    TreeNode* D = new TreeNode(15);
    A->right->left = D;
    TreeNode* E = new TreeNode(7);
    A->right->right = E;

    Solution z;
    vector<vector<int>> vv = z.levelOrder(A);

    for (auto e : vv)
    {
        cout << "[";
        for (auto v : e)
        {
            cout << v << " ";
        }
        cout << "]";
    }

	return 0;
}
